package com.xs.common.bean;


import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * @author xs
 * date 2018/3/24 17:29
 */
public class FindChange {

    public <T> String getBeanChangeInfo(T oldBean, T newBean) {
        if (oldBean == null && newBean == null) {
            return null;
        }
        StringBuilder str = new StringBuilder();
        try {
            Class clazz = oldBean.getClass();
            Field[] fields = oldBean.getClass().getDeclaredFields();
            for (Field field : fields) {
                if ("serialVersionUID".equals(field.getName()) || !field.isAnnotationPresent(Attribute.class)) {
                    continue;
                }
                PropertyDescriptor pd = new PropertyDescriptor(field.getName(), clazz);
                Method getMethod = pd.getReadMethod();
                Object o1 = getMethod.invoke(oldBean);
                Object o2 = getMethod.invoke(newBean);

                Attribute attribute = field.getAnnotation(Attribute.class);
                if (attribute.isPojo()) {
                    Class cls = pd.getPropertyType();
                    o1 = o1 == null ? cls.newInstance() : o1;
                    o2 = o2 == null ? cls.newInstance() : o2;
                    String sonDiff = getBeanChangeInfo(o1, o2);
                    str.append(sonDiff);
                } else {
                    o1 = o1 == null ? "" : o1;
                    o2 = o2 == null ? "" : o2;
                    if (!o1.toString().equals(o2.toString())) {
                        if (!IEnum.class.getSimpleName().equals(attribute.enumType().getSimpleName())) {
                            IEnum[] enumConstants = attribute.enumType().getEnumConstants();
                            o1 = enumConstants[0].getDesc(o1);
                            o2 = enumConstants[0].getDesc(o2);
                        }
                        str.append("【").append(attribute.name()).append("】从【").append(o1).append("】改为了【").append(o2).append("】;");
                    }
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return str.toString();
    }
}
